/*

Input: newdata/estimation_prep_ltw18 [prepared precinct-level panel]

	
Output: Figure 11, D.14

Task: Explore partisan effects of reassignments


*/	
	
* PULL: precinct-level data
	use "$newdata/estimation_prep_ltw18.dta", clear
	
	
********************************************************************************
*	 Prep Estimation *
********************************************************************************
	
* PREP party outcomes
	
	// classify 6 largest parties in Left-Right
	gen shr_left 	= shr_dielinke + shr_spd + shr_gruene 
	lab var shr_left	"Party share LEFT (links spd grue)"
	gen shr_cons 	= shr_fdp + shr_csu  + shr_freiewaehler 
	lab var shr_cons  "Party share RIGHT (csu fw afd)"
	gen anz_left 	= anz_dielinke + anz_spd + shr_gruene 
	lab var anz_left   "Nbr Votes LEFT (links spd grue)"
	gen anz_cons 	= shr_fdp + anz_csu  + anz_freiewaehler	
	lab var anz_cons  "Nbr Votes RIGHT (csu fw afd)"
	
	// insert missings instead of zeros for party shares where party wasn't on the ballot
	foreach v of varlist shr_* {
		forvalues j =1/8 {
			qui su `v' if wahl_id==`j'
			qui replace `v' =. if r(mean)==0 & wahl_id==`j'
		}
		assert `v' <1 if !missing(`v')
		qui replace `v'= `v'*100 // rescale 0-100
	}
	
	// gen votes rel to eligible voter
	* in KOW14 und KOW20 => #votes > #eligible voters!
	foreach v of varlist anz_* {
		gen 	 rel_`v'  =  100* `v' /wahlber_gesamt if !inlist(wahl_id,3,8)
		replace  rel_`v' =  100* `v' /(wahlber_gesamt*80) if inlist(wahl_id,3,8)
		assert inrange(rel_`v',0,100)
	}	
	

********************************************************************************
*	 Party outcomes at the polling place: ALL PARTIES (Figure D14)
********************************************************************************		


	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}
	order F1event, last


	// Estimate baseline ES
	estimates clear
	global dpv dielinke spd gruene fdp csu freiewaehler
	
	foreach r in shr rel_anz {
		foreach v in $dpv {	
			qui reghdfe `r'_`v' F7event-L7event F1event $ctr $wgt if smpl_trim ==1, absorb(i.wahl_id##i.stadtbez i.sb_new) cluster(sb_new)
			estimates store `v'
					
			// store means
			qui su `r'_`v' $wgt
			local mean_`v':di %12.1f r(mean)
			local m`v'=subinstr("`mean_`v''"," ","",.)
		}		
			// Lables
			if "`r'"=="rel_anz" local title "{bf:Panel A.} Effect on Party Turnout"
			if "`r'"=="rel_anz" local ytitle "Party turnout in %" "(estimates)"		
			if "`r'"=="shr" 	local title "{bf:Panel B.} Effect on Party Vote Shares"
			if "`r'"=="shr" 	local ytitle "Party vote share in %" "(estimates)" 
			if "`r'"=="rel_anz" local gap "-6"
			if "`r'"=="shr" 	local gap "3"
			
			
			// PLOT: FIGURE D14. Effect of Reassignments on Party Vote (single parties)
			event_plot  $dpv, ///
			stub_lag(L#event ) stub_lead(F#event ) plottype(scatter) ciplottype(rcap) ///
			together perturb(-0.25(0.1)0.25) trimlead(4) trimlag(2) noautolegend ///
			graph_opt(xtitle("") ytitle("`ytitle'", size(small)) ysc(titlegap(`gap')) xlabel(-4(1)2) xtitle("Election since reassignment") ///
				legend(pos(12) order(1 "LINKE (`mdielinke' %)" 3 "SPD (`mspd' %)" 5 "Grüne (`mgruene' %)" 7 "FDP (`mfdp' %)" ///
				9 "CSU (`mcsu' %)" 11 "FW (`mfreiewaehler' %)" /*13 "AFD (`mafd')"*/) size(small) row(1) region(style(none)) title("Outcomes (means):",size(medsmall) bexpand just(left)) ) ///
				xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
				title("`title'", nobox span bexpand justification(left) size(medium)) name(`r', replace)) ///
			lag_opt1(msymbol(S) msize(small) color(purple)) lag_ci_opt1(color(purple)) ///
			lag_opt2(msymbol(O) msize(small) color(red)) lag_ci_opt2(color(red)) ///
			lag_opt3(msymbol(T) msize(small) color(green)) lag_ci_opt3(color(green)) ///
			lag_opt4(msymbol(Dh) msize(small) color(gold)) lag_ci_opt4(color(gold)) ///
			lag_opt5(msymbol(Sh) msize(small) color(black)) lag_ci_opt5(color(black)) ///
			lag_opt6(msymbol(Oh) msize(small) color(orange)) lag_ci_opt6(color(orange))
		
	}
		
	graph combine  rel_anz shr , xcommon col(1) iscale(.8)
	gr_edit .style.editstyle declared_ysize(4.7) editcopy
	graph export "$figures/Figure_D14_ES_party_outc_all.pdf", replace				
		
********************************************************************************
*	 Party outcomes at the polling place LEFT-RIGHT (Figure 11)
********************************************************************************

	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
	}
	order F1event, last

	// Estimate baseline ES
	estimates clear
	global dpv rel_anz_left shr_left rel_anz_cons  shr_cons
	
	
	foreach v of varlist $dpv {	
		  qui reghdfe `v' F7event-L7event F1event $ctr $wgt  if smpl_trim ==1, absorb(i.wahl_id##i.stadtbez i.sb_new) cluster(sb_new)
		
		estimates store `v'
		
		qui su `v' $wgt
		local mean_`v':di %12.1f r(mean)
		local m`v'=subinstr("`mean_`v''"," ","",.)
	}
		
		
	// PLOT: LEFT RIGHT PARTY TURNOUT
	event_plot  rel_anz_left  rel_anz_cons , ///
	stub_lag(L#event ) stub_lead(F#event ) plottype(scatter) ciplottype(rcap) ///
	together perturb(-0.1(0.2)0.1) trimlead(4) trimlag(2) noautolegend ///
	graph_opt(xtitle("") ytitle("Party turnout in %""(estimates)", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment") ///
		legend(pos(12) order(1 "Left-wing (`mrel_anz_left' %)" 3 "Right-wing (`mrel_anz_cons' %)") row(1) region(style(none)) size(medsmall) title("Outcomes (means):",size(medsmall) bexpand just(left))) ///
		xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
		name(turnout, replace)) ///
	lag_opt1(msymbol(O) msize(2.5pt) color(maroon)) 	lag_ci_opt1(color(maroon)) ///
	lag_opt2(msymbol(S) msize(2.5pt) color(black)) lag_ci_opt2(color(black))	
	
	
	// PLOT: LEFT RIGHT PARTY VOTE SHARES
	event_plot  shr_left shr_cons , ///
	stub_lag(L#event ) stub_lead(F#event ) plottype(scatter) ciplottype(rcap) ///
	together perturb(-0.1(0.2)0.1) trimlead(4) trimlag(2) noautolegend ///
	graph_opt(xtitle("") ytitle("Party vote share in %""(estimates)", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment") ///
		legend(pos(12) order(1 "Left-wing (`mshr_left' %)" 3  "Right-wing (`mshr_cons' %)"   ) row(1) region(style(none)) size(medsmall) title("Outcomes (means):",size(medsmall) bexpand just(left))) ///
		xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
		name(shares, replace) ) ///
	lag_opt1(msymbol(O) msize(2.5pt) color(maroon))  lag_ci_opt1(color(maroon)) ///
	lag_opt2(msymbol(S) msize(2.5pt) color(black)) lag_ci_opt2(color(black))	
	

	
* Test for equality of estimates (since different outcomes => need to duplicate data)
frame change default
frame copy default tmp, replace
frame tmp{	
	// duplicate dataset
	gen id=_n
	expand 2
	
	// gen dataset id
	bys id: gen idset = _n-1
	
	// rename outcomes
	gen 	y_shr = shr_left 	 if idset==1
	replace	y_shr = shr_cons 	 if idset==0
	gen 	y_rel = rel_anz_left if idset==1
	replace	y_rel = rel_anz_cons if idset==0	
	
	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen 	F`l'event = K==-`l'
		gen 	F`l'event_int =F`l'event*idset	// interact w/ dataset id
	}	
	forvalues l = 0/7 {
		gen 	L`l'event = K==`l'
		gen 	L`l'event_int =L`l'event*idset
	}
	order *_int, last
	order F1event*, last

	// Estimate baseline ES
	estimates clear

	global dpv y_rel y_shr 
	
	
	foreach v of varlist $dpv {	
		  reghdfe `v' F7event-L7event F7event_int-L7event_int F1event F1event_int c.(${ctr})##c.idset $wgt if smpl_trim ==1, ///
			absorb(i.wahl_id##i.stadtbez##idset i.sb_new##idset) cluster(sb_new)
		
		estimates store `v'
					
		// PLOT: DIFFERENCES
		event_plot  `v', ///
		stub_lag(L#event_int ) stub_lead(F#event_int ) plottype(connect) ciplottype(rcap) ///
		together  trimlead(4) trimlag(2)  noautolegend ///
		graph_opt(ytitle("Difference between estimates", size(medsmall)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
			legend(pos(12) order(1 "Difference between estimates" ) row(1) region(style(none)) size(medsmall) title(" ")) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			name(`v',replace) ) ///
		lag_opt1(msymbol(T) msize(2.5pt) color(black) lcol(gray)) 	lag_ci_opt1(color(black))		
	}
}	
	
	* FIGURE 11. Effects of Reassignments on Party Outcomes (left-right): 4x Graph
	graph combine turnout y_rel, row(1) 		imargins(small) xcommon ycommon name(gr1, replace) ///
		title("{bf:Panel A.} Effect on Party Turnout", nobox span bexpand justification(left) size(medsmall) )
	graph combine shares y_shr, row(1) imargins(small) xcommon ycommon name(gr2, replace) ///
		title("{bf:Panel B.} Effect on Party Vote Shares", nobox span bexpand justification(left) size(medsmall) )
	
	graph combine gr1 gr2, xcommon col(1) imargins(small) iscale(.9)	
	gr_edit .style.editstyle declared_ysize(4.2) editcopy	
	graph export "$figures/Figure_11_ES_party_outc_two.pdf", replace		
	
	